<template>
  <div>
      <van-nav-bar title="注册" left-arrow @click-left="$router.back()" />

      <h1> 优点达资讯 </h1>

       <van-form @submit="onSubmit" submit-on-enter>
        <van-field
          v-model="username"
          name="用户名"
          label="用户名"
          placeholder="用户名"
          :rules="[{ required: true, message: '请填写用户名' }]"
        />
        <van-field
          v-model="password"
          type="password"
          name="密码"
          label="密码"
          placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]"
        />
        <van-field
          v-model="passwordto"
          type="password"
          name="再次输入密码"
          label="确认密码"
          placeholder="再次输入密码"
          :rules="[{ required: true, message: '两次密码不一致' }]"
        />
        <div style="margin: 16px;">
          <van-button round block type="info" native-type="submit">提交</van-button>
        </div>
      </van-form>
      <p class="font"><a @click.prevent="registered"> 已有账号？去登陆 </a></p>
  </div>
</template>

<script>
import { registered } from '@/api/registered'

export default {
  name: 'registered',

  data () {
    return {
      username: '',
      password: '',
      passwordto: '',
      rules: {
        mobile: [
          { required: true, message: '手机号不能为空' },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '手机号码格式错误'
          }
        ],
        code: [
          { required: true, message: '密码不能为空' },
          {
            pattern: /^\d{6}$/,
            message: '密码格式错误'
          }
        ],
        passwordto: [
          { required: true, message: '密码不能为空' },
          {
            validator: value => {
              return value === this.password
            },
            message: '两次密码不一致'
          }
        ]
      }
    }
  },

  methods: {
    async onSubmit () {
      const { data: res } = await registered(this.username, this.password)
      console.log(res)

      this.$toast(res.errmsg)

      if (res.errno === 0) {
        this.$router.push('/login')
      }
    },
    registered () {
      this.$router.push('/login')
    }
  }

}
</script>

<style>

h1 {
  text-align: center;
  font-weight: 400;
  color: skyblue;
}

.font {
  margin-right: 1.4rem;
  text-align: right;
  font-size: 12px;
  color: blue;
}

</style>
